package com.customview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import com.customview.inputview.CustomTextWatcher;


/**
 * Created by lkq on 2017/12/24.
 */

public class ViewHelper {
    /**
     * 是否可以竖直滑动
     *
     * @param editText
     * @return
     */
    private static boolean canVerticalScroll(EditText editText) {
        int scrollY = editText.getScrollY();
        int scrollRange = editText.getLayout().getHeight();
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        int scrollDifference = scrollRange - scrollExtent;
        return scrollY > 0 || scrollY < scrollDifference - 1;
    }

    @SuppressLint("ClickableViewAccessibility")
//    public static void setEditTextTouchListener(final ViewGroup viewGroup, final NoEmojiEditText editText) {
    public static void setEditTextTouchListener(final ViewGroup viewGroup, final EditText editText) {
        editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (canVerticalScroll(editText)) {
                    viewGroup.requestDisallowInterceptTouchEvent(true);
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        viewGroup.requestDisallowInterceptTouchEvent(false);
                    }
                }
                return false;
            }
        });

    }

    /**
     * listView是否滑动到底部
     */

    public static boolean isListViewReachBottomEdge(final AbsListView listView) {
        boolean result = false;
        if (listView.getLastVisiblePosition() == (listView.getCount() - 1)) {
            final View bottomChildView = listView.getChildAt(listView.getLastVisiblePosition() - listView.getFirstVisiblePosition());
            result = (listView.getHeight() >= bottomChildView.getBottom());
        }
        return result;
    }

    /**
     * TextView设置DrawableLeft
     */
    public static void setDrawableLeft(TextView textView, int res, Context context) {
        Drawable drawable = context.getResources().getDrawable(res);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        textView.setCompoundDrawables(drawable, null, null, null);
    }

    /**
     * TextView设置DrawableTop
     */
    public static void setDrawableTop(TextView textView, int res, Context context) {
        Drawable drawable = context.getResources().getDrawable(res);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        textView.setCompoundDrawables(null, drawable, null, null);
    }

    /**
     * TextView设置DrawableBottom
     */
    public static void setDrawableBottom(TextView textView, int res, Context context) {
        Drawable drawable = context.getResources().getDrawable(res);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        textView.setCompoundDrawables(null, null, null, drawable);
    }

    /**
     * TextView设置DrawableRight
     */
    public static void setDrawableRight(TextView textView, int res, Context context) {
        Drawable drawable = context.getResources().getDrawable(res);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        textView.setCompoundDrawables(null, null, drawable, null);
    }

    /**
     * TextView设置Drawable为空
     */
    public static void clearCompoundDrawables(TextView textView) {
        textView.setCompoundDrawables(null, null, null, null);
    }

    /**
     * 解决EditText在过滤掉emoji表情之后对xml中的maxLength属性不起作用的问题
     */
    public static void setMaxLengthAndEmojiFilter(EditText editText, int length) {
        InputFilter inputFilters = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int index = start; index < end; index++) {
                    int type = Character.getType(source.charAt(index));
                    if (type == Character.SURROGATE) {
                        return "";
                    }
                }
                return null;
            }
        };
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(length), inputFilters});
    }


    public static void hightObserve(final HightObserveCallBack callBack, final EditText... editTexts) {
        for (EditText editText : editTexts) {
            editText.addTextChangedListener(new CustomTextWatcher() {
                @Override
                public void afterChanged(Editable s) {
                    callBack.callBack(isHight(editTexts));
                }
            });
        }
    }

    private static boolean isHight(EditText... editTexts) {
        for (EditText editText : editTexts) {
            if (TextUtils.isEmpty(editText.getText().toString())) {
                return false;
            }
        }
        return true;
    }

    public static void setProtocolSpan(TextView tv, String originContent, int protocolColor, OnProtocolClickListener onItemClickListener) {
        List<Range> list = new ArrayList<>();
        for (int i = -1; i <= originContent.lastIndexOf("《"); ++i) {
            i = originContent.indexOf("《", i);
            list.add(new Range(i, 0));
            String substring = originContent.substring(i, originContent.length());
            list.get(list.size() - 1).end = substring.indexOf("》") + i + 1;
        }

        SpannableStringBuilder content = new SpannableStringBuilder(originContent);
        for (int i = 0; i < list.size(); i++) {
            Range range = list.get(i);
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(protocolColor);
            content.setSpan(colorSpan, range.start, range.end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            BlankClickableSpan blankClickableSpan = new BlankClickableSpan(i, onItemClickListener, originContent.substring(list.get(i).start + 1, list.get(i).end - 1));
            content.setSpan(blankClickableSpan, range.start, range.end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setText(content);
    }

    static class BlankClickableSpan extends ClickableSpan {
        private OnProtocolClickListener mOnItemClickListener;
        private int position;
        private String title;

        BlankClickableSpan(int position, OnProtocolClickListener onItemClickListener, String title) {
            this.position = position;
            mOnItemClickListener = onItemClickListener;
            this.title = title;
        }

        @Override
        public void onClick(final View widget) {
            mOnItemClickListener.onItemClick(position, title);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setUnderlineText(false);
        }
    }

    public static int getListViewItemHeight(ListView listView, View v, int index) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return -1;
        }

        int totalHeight = 0;
        for (int i = 0; i < index; i++) { // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }

        if (v != null) {
            totalHeight += v.getMeasuredHeight();
        }
        return totalHeight /*+ (listView.getDividerHeight() * (listAdapter.getCount() - 1))*/;
    }

    public interface HightObserveCallBack {
        void callBack(boolean isHight);
    }

    public interface OnProtocolClickListener {
        void onItemClick(int position, String title);
    }

    static class Range {
        public int start;
        public int end;

        public Range(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }
}
